using System;
using System.Collections.Generic;
using System.Text;
using GameViewer.Core.Viewers;

namespace GameViewer.Core
{
    public class ViewerManager : Singleton<ViewerManager>
    {
        Dictionary<string, Type> mViewerTypes = new Dictionary<string, Type>();
        Dictionary<string, Viewer> mViewers = new Dictionary<string, Viewer>();

        public ViewerManager()
        {
            AddViewer("txt", typeof(TextViewer));
            AddViewer("html", typeof(TextViewer));
            AddViewer("ini", typeof(TextViewer));
            AddViewer("cfg", typeof(TextViewer));
            AddViewer("xml", typeof(TextViewer));

            AddViewer("png", typeof(TextureViewer));
            AddViewer("jpg", typeof(TextureViewer));
            AddViewer("tga", typeof(TextureViewer));

            AddViewer("m2", typeof(MeshViewer));

            AddViewer("hex", typeof(HexViewer));
        }

        public void AddViewer(string type, Type viewer)
        {
            if (mViewerTypes.ContainsKey(type) == false)
            {
                LogManager.Instance.LogMessage("Registering Viewer: " + type +".");
                mViewerTypes.Add(type, viewer);
            }
        }

        private Viewer GetView(Type type)
        {
            string typeName = type.Name;
            if (mViewers.ContainsKey(typeName))
            {
                return mViewers[typeName];
            }

            Viewer viewer = (Viewer)Activator.CreateInstance(type);
            mViewers.Add(typeName, viewer);
            viewer.Disposed += new EventHandler(viewer_Disposed);
            return viewer;
        }

        void viewer_Disposed(object sender, EventArgs e)
        {
            string typeName = sender.GetType().Name;
            mViewers.Remove(typeName);
        }

        public Viewer View(string type, Archives.FileInfo file)
        {
            Viewer viewer = null;
            if (mViewerTypes.ContainsKey(type))
            {
                viewer = GetView(mViewerTypes[type]);
            }
            else
            {
                viewer = GetView(mViewerTypes["hex"]);
            }
            viewer.View(file);
            MainForm.Instance.SetViewer(viewer);
            return viewer;
        }

        public Viewer View(Archives.FileInfo file)
        {
            string type = System.IO.Path.GetExtension(file.FileName).ToLower();
            if (string.IsNullOrEmpty(type) == false)
            {
                type = type.Remove(0, 1);
            }
            return View(type, file);
        }
    }
}
